<template>
  <el-dialog
    title="在线签名"
    width="400px"
    :visible.sync="dialogVisible"
    :before-close="dialogBeforeClose"
  >
    <div class="content">
      <el-alert
        style="margin-bottom: 15px"
        type="error"
        :center="false"
        :closable="false"
        description="请录入个人签名，用于业务单据导出或审批。如需维护签名信息，请去签名管理功能菜单进行操作。"
      >
      </el-alert>
      <span :style="qrStyle">请使用微信或交建通扫一扫签名</span>
      <vue-qr
        :style="qrStyle"
        :logoSrc="imageUrl"
        :text="imageText"
        :size="180"
      />
      <div :style="textStyle">请在手机上进行操作</div>
      <div :style="textStyle" class="tooltip">* 签名完成前请勿关闭此窗口</div>
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from "lodash";
import vueQr from "vue-qr";
import { getArgs, generateUUID, getSessionItem } from "@/basa/utils";
import {
  qrySmpAutograph,
  qrySmpAutographById,
  qrySmpAutographCode,
  getUserInfo
} from "@/basa/api";
export default {
  name: "exportQr",
  props: {
    type: {
      type: String,
      default: "approval"
    }
  },
  components: {
    vueQr
  },
  data() {
    return {
      dialogVisible: false,
      imageUrl: "",
      imageText: "",
      fiveMinute: 1000 * 60 * 5,
      threeMinute: 1000 * 60 * 3,
      qrCodeTimer: null, // 二维码有效期
      qrCodeLifeTimer: null, // 二维码生命周期
      ScanCodeTimer: null, // 是否扫码
      autographTimer: null, // 是否签名
      qrStyle: { display: "block" },
      textStyle: { display: "none" },
      openId: ""
    };
  },
  watch: {
    threeMinute(newVal) {
      if (newVal === 0) {
        this.$showErrorMessage("抱歉，二维码已失效!");
        this.dialogBeforeClose();
      }
    },
    fiveMinute(newVal) {
      if (newVal === 0) {
        this.$showErrorMessage("操作超时，请重新操作!");
        this.dialogBeforeClose();
      }
    }
  },
  methods: {
    init() {
      if (this.type === "approval") {
        const createUserId = getSessionItem("userInfo").openId;
        this.queryAutograph({ createUserId });
      } else if(this.type === "login"){
        getUserInfo(
            this.$addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",
            {}
        ).then(res => {
          const { userInfo } = res.data.data;
          localStorage.setItem("curentUserName", userInfo.name);
        });
        this.qrySmpAutograph();
      } else {
        this.qrySmpAutograph();
      }
    },

    // 查询是否有历史签名
    async qrySmpAutograph() {
      const createUser = localStorage.getItem("curentUserName");
      // isAlert 是否弹框 1是 0 否  ；isFirst 是否第一次弹出 1是 0 否
      const { isAlert, isFirst } = (await qrySmpAutograph({ createUser })).data
        .data;
      if (!!isAlert && !!isFirst) this.showDialogVisible();
    },

    async queryAutograph(obj = {}) {
      // 存一下当前状态
      let oldType = cloneDeep(this.type);

      // 先调接口判断是否签过名
      const { id, base64Code } = (await qrySmpAutographById(obj)).data.data;
      this.type = !base64Code ? "create" : "edit";
      // 没签名
      if (!base64Code) return this.showDialogVisible(id);
      // 有签名
      if (oldType !== "approval" && this.type === "edit") {
        this.showDialogVisible(id);
      }
    },

    showDialogVisible(id = null) {
      // 设置二维码路径
      const url = this.$addUrlPerFix(process.env.VUE_APP_BASE_URL);
      const uuid = generateUUID();
      const { appId, openId, orgId } = getSessionItem("userInfo");
      this.openId = openId;
      const createUser = encodeURIComponent(
        localStorage.getItem("curentUserName")
      );

      // 生成二维码路径
      this.imageText = `${url}/generateQrCode.html?a=${getArgs(
        "a"
      )}&uuId=${uuid}&type=${
        this.type
      }&id=${id}&appId=${appId}&openId=${openId}&orgId=${orgId}&createUser=${createUser}&timestamp=${new Date().getTime()}`;

      // 显示弹窗
      this.dialogVisible = true;

      // 触发二维码有效期倒计时
      this.qrCodeTimer = setInterval(() => {
        this.threeMinute -= 1000;
      }, 1000);

      // 触发二维码生命周期倒计时
      this.qrCodeLifeTimer = setInterval(() => {
        this.fiveMinute -= 1000;
      }, 1000);

      // 定时任务接口

      // 检测手机是否扫码/检测手机是否生成签名
      this.ScanCodeTimer = setInterval(() => {
        this.qrySmpAutographCode(uuid, 2);
      }, 2000);
    },

    // 检测手机是否扫码/检测手机是否生成签名
    async qrySmpAutographCode(uuId, operation) {
      const obj = { uuId, operation };
      const { isScan, isSave } = (await qrySmpAutographCode(obj)).data.data;
      // 返参： isScan:  二维码是否扫描 1是 0否     isSave：//是否保存 1是 0否
      if (isScan) {
        clearInterval(this.qrCodeTimer);
        this.qrStyle = { display: "none" };
        this.textStyle = { display: "block" };
      }
      if (isSave) {
        this.$message.success("签名成功！");
        this.$emit("ok");
        this.dialogVisible = false;
        this.dialogBeforeClose();
      }
    },

    destroyReset() {
      clearInterval(this.qrCodeTimer);
      this.qrCodeTimer = null;

      clearInterval(this.qrCodeLifeTimer);
      this.qrCodeLifeTimer = null;

      clearInterval(this.ScanCodeTimer);
      this.ScanCodeTimer = null;

      this.qrStyle = { display: "block" };
      this.textStyle = { display: "none" };

      this.$nextTick(() => {
        this.threeMinute = 1000 * 60 * 3;
        this.fiveMinute = 1000 * 60 * 5;
      });
    },

    dialogBeforeClose() {
      this.dialogVisible = false;
      this.destroyReset();
    }
  },
  activated() {
    if (this.type !== "edit") this.init();
  }
};
</script>

<style lang="scss" scoped>
.content {
  text-align: center;
  img {
    margin: 0 auto;
  }
  .tooltip {
    color: red;
    margin-top: 10px;
  }
}
/deep/.el-alert--error.is-light .el-alert__description {
  margin: 0;
  text-align: left;
}
</style>
